from flask import Flask, request, g
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from .translations import translations

db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
login_manager.login_view = 'admin.login'
login_manager.login_message = '請先登錄！'
login_manager.login_message_category = 'info'

def create_app():
    app = Flask(__name__,
                template_folder='templates',  # 相对于app包的路径
                static_folder='static')
    app.config['SECRET_KEY'] = 'your-secret-key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    db.init_app(app)
    migrate.init_app(app, db)  # 初始化迁移
    login_manager.init_app(app)
    
    @app.template_filter('t')
    def translate_filter(text):
        lang = request.args.get('lang', 'zh')
        if lang not in ['zh', 'en']:
            lang = 'zh'
        return translations[lang].get(text, text)

    @app.before_request
    def before_request():
        g.lang = request.args.get('lang', 'zh')
        if g.lang not in ['zh', 'en']:
            g.lang = 'zh'

    # 确保在app上下文内导入路由
    with app.app_context():
        from .routes.front import front
        from .routes.admin import admin
        app.register_blueprint(front)
        app.register_blueprint(admin, url_prefix='/admin')
        
        # 创建所有数据库表
        db.create_all()
    
    return app 